import axios from 'axios'
import { ElNotification, ElMessageBox } from 'element-plus'


const request = axios.create({
    baseURL: 'http://localhost:3000',
})

request.interceptors.request.use(function (config) {
    // console.log(config)
    const loginInfo = localStorage.getItem('login')
    if (loginInfo) {
        const { access_token } = JSON.parse(loginInfo)
        config.headers.Authorization = `Bearer ${access_token}`
    }
    return config
}, function (error) {
    console.log('response.error', error)
    return Promise.reject(error)
})

request.interceptors.response.use((response) => {
    // 如果是Blob类型的响应，直接返回
    if (response.config.responseType === 'blob') {
        return response.data
    }
    
    if (response.data.code === 200) {
        return response.data
    } else {
        ElNotification({
            title: 'Error',
            message: response.data.message,
            type: 'error',
        })
        return Promise.reject(response.data)
    }
}, (error) => {
    console.log(error)
    ElNotification({
        title: 'Error',
        message: error.response.data.message,
        type: 'error',
    })
    if (error.response.data.code === 401) {
        localStorage.removeItem('login')
        ElMessageBox.alert('您已被登出，是否重新登录？', '系统提示', {
            confirmButtonText: '重新登陆',
            callback() {
                window.location.href = '/login'
            }
        })
    }
    return Promise.reject(error.response.data)
})

export default request